﻿<%@ WebHandler Language="C#" Class="ajaxproductinfo" %>

using System;
using System.Web;
using System.Web.SessionState;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using GZ.Entity;
using System.Web.Script.Serialization;
using System.IO;
/// <summary>
/// 产品ajax处理方法
/// </summary>
public class ajaxproductinfo : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{

    HttpRequest Request;
    HttpResponse Response;
    HttpSessionState Session;
    HttpServerUtility Server;
    HttpCookie Cookie;

    public void ProcessRequest(HttpContext context)
    {
        Request = context.Request;
        Response = context.Response;
        Session = context.Session;
        Server = context.Server;
        string method = Request["methodName"].ToString();
        System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(method);
        methodInfo.Invoke(this, null);
    }
    /// <summary>
    /// 初始化所有分类
    /// </summary>
    public void InitProCates()
    {
        ECategory cateAccessor = new ECategory();
        Response.Write(JsonConvert.SerializeObject(cateAccessor.GetCategory()));
    }
    /// <summary>
    /// 立即购物购物车初始化 
    /// </summary>
    public void QueryProductsByCid()
    {
        StringBuilder productCarts = new StringBuilder();
        StringBuilder productItems = new StringBuilder();
        String[] cids = null;
        String[] carts = null;
        String s = Request.Cookies["totalCates"].Value;
        String c = Request.Cookies["carList"].Value;
        GZ.Entity.EProductInfo dal = new GZ.Entity.EProductInfo();
        String _cid = String.Empty;
        String _pid = String.Empty;
        if (!String.IsNullOrEmpty(s) && !String.IsNullOrEmpty(c))
        {
            cids = s.IndexOf("_") != -1 ? s.Split(new String[] { "_" }, StringSplitOptions.RemoveEmptyEntries) : new String[] { s };
            carts = c.IndexOf("&") != -1 ? c.Split(new String[] { "&" }, StringSplitOptions.RemoveEmptyEntries) : new String[] { c };
            productCarts.Append("[");
            String[] ars = null;
            for (int i = 0; i < cids.Length; i++)
            {
                productCarts.Append("{\"cid\":\"" + cids[i] + "\",\"values\"" + ":[");

                foreach (String item in carts)
                {
                    ars = item.Split(new String[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                    _cid = ars[3];
                    _pid = ars[0].Split(new String[] { "=" }, StringSplitOptions.RemoveEmptyEntries)[0];

                    if (String.Compare(cids[i], _cid) == 0)
                    {
                        GZ.Entity.EProductInfo pro = dal.GetProductInfoById(Convert.ToInt32(_pid));
                        string sssss = JsonConvert.SerializeObject(pro).TrimEnd(new char[] { '}' }) + ",\"quantity\":\"" + ars[1] + "\"}";
                        productItems.Append(sssss + ",");
                    }
                }

                if (productItems.Length == 0)
                {
                    productCarts.Append(productItems.Append("]}"));
                }
                else
                {
                    productCarts.Append(productItems.ToString().TrimEnd(new char[] { ',' }) + "]}");
                }
                productItems = new StringBuilder();
                if (i != cids.Length - 1)
                {
                    productCarts.Append(",");
                }
            }
            productCarts.Append("]");
        }
        Response.Write(productCarts.ToString());
    }



    /// <summary>
    /// 获取指定产品
    /// </summary>
    public void QueryProductById()
    {
        GZ.Entity.EProductInfo dal = new GZ.Entity.EProductInfo();
        Int32 pid = 0;
        String spid = Request.QueryString["pid"];
        if (!String.IsNullOrEmpty(spid))
        {
            if (int.TryParse(spid, out pid))
            {
                Response.Write(JsonConvert.SerializeObject(dal.GetProductInfoById(pid)));
            }
            else
            {
                Response.Write("{}");
            }
        }
        else
        {
            Response.Write("{}");
        }
    }

    /// <summary>
    ///把指定产品信息加入购物车
    /// </summary>
    public void IntoShoppingCart()
    {
        int pid;
        string result = string.Empty;
        if (int.TryParse(Request.QueryString["pid"], out pid))
        {
            GZ.Entity.EProductInfo dal = new GZ.Entity.EProductInfo();
            GZ.Entity.EProductInfo product = dal.GetProductInfoById(pid);
            product.ProductName = HttpUtility.UrlEncode(product.ProductName);
            product.ShoppingCartThumbUrl = HttpUtility.UrlEncode(product.ShoppingCartThumbUrl);
            product.ProductStyle = HttpUtility.UrlEncode(product.ProductStyle);
            if (product != null)
            {
                //判断购物车中是否已经存在
                String cart = CurrentCart;
                String p = product.ToString().TrimStart(new char[] { '{' }).TrimEnd(new char[] { '}' });

                if (!String.IsNullOrEmpty(cart))
                {
                    if (!CurrentProIsExistProducts(product.Id.ToString()))
                    {
                        result = GZ.Common.JsonHelper.ToJson<EProductInfo>(product);
                        result = result.Remove(result.Length - 1);
                        result += ",\"state\":\"0\"}";
                    }
                    else
                    {
                        result = GZ.Common.JsonHelper.ToJson<EProductInfo>(product);
                        result = result.Remove(result.Length - 1);
                        result += ",\"state\":\"1\"}";
                    }
                }
                else
                {
                    result = GZ.Common.JsonHelper.ToJson<EProductInfo>(product);
                    result = result.Remove(result.Length - 1);
                    result += ",\"state\":\"0\"}";
                }
            }
            else
            {
                result = GZ.Common.JsonHelper.ToJson<EProductInfo>(product);
                result = result.Remove(result.Length - 1);
                result = "{\"state\":\"-1\"}";
            }
        }
        Response.Write(result);
    }

    /// <summary>
    /// 购物车中是否存在当前商品
    /// </summary>
    /// <returns></returns>
    public bool CurrentProIsExistProducts(String pid)
    {
        bool isExist = false;
        if (!String.IsNullOrEmpty(CurrentCart))
        {
            if (CurrentCart.IndexOf("&") > -1)
            {
                String[] carts = CurrentCart.Split(new char[] { '&' });

                for (int i = 0; i < carts.Length; i++)
                {
                    if (carts[i].Split(new char[] { '|' })[0].Split(new char[] { '=' })[0] == pid)
                    {
                        isExist = true;
                        break;
                    }
                }
            }
            else
            {
                if (CurrentCart.Split(new char[] { '|' })[0].Split(new char[] { '=' })[0] == pid)
                {
                    isExist = true;
                }
            }
        }
        return isExist;
    }


    public String CurrentCart
    {
        get
        {
            if (Request.Cookies["carList"] != null)
            {
                return Request.Cookies["carList"].Value;
            }
            return String.Empty;
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

